<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">
        function thunkify(fn) {
            //全局返回一个临时函数
            return function () {
                var args = new Array(arguments.length);
                var ctx = this;

                for (var i = 0; i < args.length; ++i) {
                    args[i] = arguments[i];
                }
                //上面一段将参数copy到args

                return function (done) {
                    var called;
                    args.push(function () {
                        if (called) return; //对callback重新包装，控制callback只执行一次
                        called = true;
                        done.apply(null, arguments);//执行传进来的参数的apply方法
                    });

                    try {
                        fn.apply(ctx, args);
                    } catch (err) {
                        done(err);
                    }
                }
            }
        };

        function f(a, b, callback) {
            var sum = a + b;
            callback(sum);
        }

        var ft = thunkify(f);
        ft(1, 2)(console.log); 
    </script>
</body>

</html>